<?php

namespace app\push\controller;

use think\Cache;
use think\worker\Server;

class ChannelClient extends Server
{
    protected $socket = 'websocket://www.thinkphp.cc:4236';

    /**
     * 收到信息
     * @param $connection
     * @param $data
     */
    public function onMessage($connection, $data)
    {
        $toConnectionIds = Cache::store('redis')->get('toConnectionIds')?: [];
        $code = json_decode($data, true)['code'];
        if(isset($toConnectionIds[$code])){
            array_push($toConnectionIds[$code], $connection->id);
        }else{
            $toConnectionIds = [$code => [$connection->id]];
        }
        Cache::store('redis')->set('toConnectionIds', $toConnectionIds);
    }

    /**
     * 当连接建立时触发的回调函数
     * @param $connection
     */
    public function onConnect($connection)
    {
        $msg = "workerID:{$connection->worker->id} connectionID:{$connection->id} connected\n";
        // 显示在命令行
        echo $msg;
        // 回复到链接中
        $connection->send($msg);
    }

    /**
     * 当连接断开时触发的回调函数
     * @param $connection
     */
    public function onClose($connection)
    {
        $toConnectionIds = Cache::store('redis')->get('toConnectionIds')?: [];
        $reverseIdArray = array_flip($toConnectionIds);
        unset($toConnectionIds[$reverseIdArray[$connection->id]]);
        Cache::store('redis')->set('toConnectionIds', $toConnectionIds);
    }

    /**
     * 当客户端的连接上发生错误时触发
     * @param $connection
     * @param $code
     * @param $msg
     */
    public function onError($connection, $code, $msg)
    {
        echo "error $code $msg\n";
    }

    /**
     * 每个进程启动
     * @param $worker
     */
    public function onWorkerStart($worker)
    {
        // Channel客户端连接到Channel服务端
        \Channel\Client::connect('127.0.0.1', 2206);

        // 注册方法事件及 callback
        
        // 以自己的进程id为事件名称
        $event_name = $worker->id;
        // 订阅worker->id事件并注册事件处理函数
        \Channel\Client::on($event_name, function($event_data)use($worker){
            $to_connection_id = $event_data['to_connection_id'];
            $message = $event_data['content'];
            if(!isset($worker->connections[$to_connection_id]))
            {
                echo "connection not exists\n";
                return;
            }
            $to_connection = $worker->connections[$to_connection_id];
            $to_connection->send($message);
        });

        // 订阅广播事件
        $event_name = '广播';
        // 收到广播事件后向当前进程内所有客户端连接发送广播数据
        \Channel\Client::on($event_name, function($event_data)use($worker){
            $message = $event_data['content'];
            foreach($worker->connections as $connection)
            {
                $connection->send($message);
            }
        });

        Cache::store('redis')->set('toConnectionIds', []);
    }
    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function index()
    {
        return 'index';
    }

    protected function init()
    {

    }

    
}
